package cn.kgc.vue.aop;

import cn.kgc.vue.entity.LogInfo;
import cn.kgc.vue.mapper.LogInfoMapper;
import cn.kgc.vue.utils.IpUtil;
import cn.kgc.vue.utils.JWTUtil;
import lombok.extern.java.Log;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;

/***
 *@title AopConfig
 *@author 韩旭
 *@version 1.0.0
 *@create 2023/8/20 22:26
 **/
@Component
@Aspect
@Log
public class AopConfig {
    @Autowired
    private LogInfoMapper logInfoMapper;
    @Pointcut("@annotation(cn.kgc.vue.aop.AopLog)")
    public void aop(){}
    @Around("aop()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("aaaaaaaa");
        LogInfo logInfo = new LogInfo();
        Object[] args = joinPoint.getArgs();
        //方法参数
        String params = Arrays.toString(args);
        //获取方法
        MethodSignature signature =(MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        AopLog annotation = method.getAnnotation(AopLog.class);
        String description = annotation.opration().getRation();
        String model = annotation.model();
        //获取ip和username，url
        //获取request对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String uri = request.getRequestURI();
        //获取url
        String ip = IpUtil.getIp(request);
        //获取用户名
        String token = request.getHeader("token");
        String username =(String) JWTUtil.getClaim(token).get("username");
        logInfo.setIp(ip);
        logInfo.setParams(params);
        logInfo.setUsername(username);
        logInfo.setUrl(uri);
        logInfo.setDescription(description);
        logInfo.setModel(model);
        logInfoMapper.insert(logInfo);
        Object proceed = joinPoint.proceed();
        return proceed;
    }

}
